package com.heima.article.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.dtos.ResponseResult;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.pojo.ApArticle;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.heima.common.constants.ArticleConstants.*;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    // 单页最大加载的数字
    private final static int MAX_PAGE_SIZE = 50;
    // 单页最小加载的数字
    private final static int MIN_PAGE_SIZE = 10;

    @Resource
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult<List<ApArticle>> load(Short loadType, ArticleHomeDto dto) {
        //1.校验参数
        int size = Convert.toInt(dto.getSize(), MIN_PAGE_SIZE);
        size = Math.max(size, MIN_PAGE_SIZE);
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数检验
        if (ObjectUtil.notEqual(loadType, LOADTYPE_LOAD_MORE) && ObjectUtil.notEqual(loadType, LOADTYPE_LOAD_NEW)) {
            loadType = LOADTYPE_LOAD_MORE;
        }

        //文章频道校验
        if (StrUtil.isEmpty(dto.getTag())) {
            dto.setTag(DEFAULT_TAG);
        }

        //时间校验
        if (ObjectUtil.isEmpty(dto.getMaxBehotTime())) {
            dto.setMaxBehotTime(new Date());
        }
        if (ObjectUtil.isEmpty(dto.getMinBehotTime())) {
            dto.setMinBehotTime(new Date());
        }

        //2.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);

        //3.结果封装
        return ResponseResult.okResult(apArticles);
    }
}

